package com.example.demo.validator.impl;

import com.example.demo.common.constant.StatusBusiness;
import com.example.demo.common.exception.BusinessException;
import com.example.demo.util.DateUtil;
import com.example.demo.validator.DateValidator;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;

public class DateTimeHandle implements ConstraintValidator<DateValidator, String> {
    private DateValidator dateValidator;

    @Override
    public void initialize(DateValidator dateValidator) {
        this.dateValidator = dateValidator;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        String format = dateValidator.format();
        String validatorVal = dateValidator.value();
        // 如果传入值为空 并且属性上加入 @NotBlank @NotNull等注解 会进入下个注解校验
        if (StringUtils.isNotBlank(value)) {
            if (!DateUtil.isValidDate(value, format))
                throw new BusinessException(StatusBusiness.FAILD.getStatus(), "传入日期格式错误或非法！");
            if (!StringUtils.equalsAny(validatorVal, DateValidator.BEFORENOW, DateValidator.AFTERNOW)) {
                throw new ValidationException("@DateValidator注解value值配置异常！");
            }
            String now = DateUtil.getLocalDateStr(format);
            // 判断date1和date2的大小，大于返回1，等于返回0，小于返回-1
            int result = now.compareTo(value);
            // 当前时间必须大于输入时间
            if (DateValidator.AFTERNOW.equals(validatorVal) && result > 0) {
                throw new ValidationException(dateValidator.message());
            }
            // 当前时间必须小于输入时间
            if (DateValidator.BEFORENOW.equals(validatorVal) && result < 0) {
                throw new ValidationException(dateValidator.message());
            }
        }
        return true;
    }
}
